package com.googlecode.geoteacher;

import java.text.DateFormat;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.googlecode.geoteacher.db.DataSource;
import com.googlecode.geoteacher.db.DatabaseContract;
import com.googlecode.geoteacher.db.model.ChallengeResult;

public class EvaluationActivity extends Activity {

	private static final String INTENT_PREFIX = "com.googlecode.geoteacher.Evaluation.";

	public static final String INTENT_AVERAGE_DISTANCE = INTENT_PREFIX
			+ "average_distance";

	public static final String INTENT_LIST_PLACES = INTENT_PREFIX
			+ "places_list";

	public static final String INTENT_LIST_DISTANCES = INTENT_PREFIX
			+ "distances_list";

	public static final String INTENT_CHALLENGE_ID = INTENT_PREFIX
			+ "challenge_id";

	private TextView avgDistView;
	private LinearLayout detailResults;
	private LinearLayout lastResults;

	private DataSource datasource;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_evaluation);
		// Show the Up button in the action bar.
		setupActionBar();

		datasource = new DataSource(this);
		datasource.open();

		avgDistView = (TextView) findViewById(R.id.average_distance);
		detailResults = (LinearLayout) findViewById(R.id.detail_results);
		lastResults = (LinearLayout) findViewById(R.id.last_results);

		initUI();
	}

	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			// getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public void onBackPressed() {
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			// NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initUI() {
		Bundle extras = getIntent().getExtras();
		LayoutInflater inflater = getLayoutInflater();

		if (extras != null) {
			avgDistView.setText(String.format(
					getString(R.string.this_avg_distance),
					extras.getInt(INTENT_AVERAGE_DISTANCE)));

			String[] places = extras.getStringArray(INTENT_LIST_PLACES);
			int[] distances = extras.getIntArray(INTENT_LIST_DISTANCES);

			final String placeSuffix = " ";

			int placeTextViewWidth = measureLongestPlaceName(places,
					placeSuffix);

			for (int i = 0; i < places.length; i++) {
				View view = inflater.inflate(R.layout.evaluation_item, null);

				TextView placeTextView = (TextView) view
						.findViewById(R.id.item_place);
				TextView distanceTextView = (TextView) view
						.findViewById(R.id.item_distance);

				placeTextView.setWidth(placeTextViewWidth);
				placeTextView.setText(places[i] + placeSuffix);
				distanceTextView.setText(String.valueOf(distances[i]) + " km");

				detailResults.addView(view);
			}
		}

		List<ChallengeResult> challengeResults = datasource
				.getAllChallengeResultsOfChallenge(
						extras.getLong(INTENT_CHALLENGE_ID),
						DatabaseContract.ChallengeResultEntry.COLUMN_DISTANCE
								+ " ASC", 10);

		final DateFormat format = android.text.format.DateFormat
				.getDateFormat(this);

		String[] dates = new String[challengeResults.size()];

		for (int i = 0; i < challengeResults.size(); i++) {
			dates[i] = format.format(challengeResults.get(i).getCreated())
					+ " : ";
		}

		final int createdTextViewWidth = measureLongestPlaceName(dates, "");

		for (int i = 0; i < challengeResults.size(); i++) {
			View view = inflater.inflate(R.layout.evaluation_item, null);

			TextView placeTextView = (TextView) view
					.findViewById(R.id.item_place);
			TextView distanceTextView = (TextView) view
					.findViewById(R.id.item_distance);

			placeTextView.setWidth(createdTextViewWidth);
			placeTextView.setText(dates[i]);
			distanceTextView.setText(String.valueOf(challengeResults.get(i)
					.getDistance()) + " km");

			lastResults.addView(view);
		}
	}

	private int measureLongestPlaceName(String[] places, String suffix) {
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.evaluation_item, null);
		TextView placeTextView = (TextView) view.findViewById(R.id.item_place);
		Paint paint = placeTextView.getPaint();

		float max = 0;

		for (int i = 0, len = places.length; i < len; ++i) {
			max = Math.max(max, paint.measureText(places[i] + suffix));
		}

		return (int) max;
	}

	public void onBackToMenu(View view) {
		finish();
	}
}